import { defineConfig } from 'vite';
import { createVuePlugin } from 'vite-plugin-vue2';
import vueUtils from './vue.utils.ts';
import path from 'path';
import htmlPlugin from './plugins/htmlPlugin.js';
import { inlineSvgPlugin } from './plugins/inlineSvgPlugin.js';
import tester from '@rollup/plugin-terser';

// 一些默认变量，根据具体命令参数进行增删
const runType = vueUtils('type', 'dev', 'string');
const runEnvType  = vueUtils('envType', '3', 'string');

export default defineConfig({
  publicDir: './public',
  plugins: [
    createVuePlugin(),
    htmlPlugin(),
    inlineSvgPlugin({
      assetsInlineLimit: Number.MAX_SAFE_INTEGER,
    }),
  ],
  server: {
    port: 3000,
    watch: {
      usePolling: true,
    },
  },
  define: {
    runType: JSON.stringify(runType),
    runEnvType: JSON.stringify(runEnvType),
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '~@': path.resolve(__dirname, './src'),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        silenceDeprecations: ['legacy-js-api'],
        additionalData: `@use "./src/styles/variables.scss" as *;`,
      },
    },
  },
  build: {
    assetsInlineLimit: Number.MAX_SAFE_INTEGER,
    // minify: false,
    copyPublicDir: false,
    emptyOutDir: true,
    target: 'es2016',
    rollupOptions: {
      // HACK: 轻应用需要打包成 umd, 但打包出来的 js 会内联 CSS，本应当需要单独打包 css，但通过尝试使用 postcss 等方式无法实现
      // 暂时通过先打包成 esm，打包出一份 CSS，再打包成 umd。
      output: [
        {
          entryFileNames: 'js/app.js',
          assetFileNames: 'css/app.css',
          format: 'esm',
        },
        {
          entryFileNames: 'js/app.js',
          assetFileNames: 'css/app.css',
          format: 'umd',
        },
      ],
      plugins: [tester({
        compress: true,
      })]
    },
  },
});
